package com.xindaoapp.happypet.ui;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

import com.baidu.location.BaiDuLocationManager;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.entry.Location;
import com.xindaoapp.happypet.shop.ui.ShopIndexFragment;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.Constants.NoticeLabel;
import com.xindaoapp.happypet.utils.Constants.PUBLISHPOSTS;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.MoccaPreferences;


public class MainActivity extends FragmentActivity implements OnClickListener {

    private View[] vBottomTabs;
    /** 消息推送底部tab红点标记 */
    private View vNoticeMessageLabelIcon;
    // MyMessageFragment.class
    private final Class[] mFragments = new Class[] {MainFragment_New.class, NearByFragment.class,
            ShopIndexFragment.class, PersonalCenterFragment_new.class};
    private final Map<Integer, Fragment> mFragmentMaps = new HashMap<Integer, Fragment>();

    private NoticeReceiver mNoticeReceiver;

    private int mCurrentSelectedPosition = -1;
    private final int SPACETIME = 2000;
    private long mLastBackPressTime;

    // 抽屉，侧拉菜单
    private DrawerLayout mDrawerLayout;
    // 侧拉菜单开关
    private ActionBarDrawerToggle taggle;
    // 自定义的处理事件冲突的ListView
    // private InterceptListView left_drawer;

    private JoinOutReciver joinOutReciver;
    private LoginSuccessReceiver loginSuccessReceiver;

    private BaiDuLocationManager locationManager;

    private final Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }

    };

    /*
     * (non-Javadoc)
     * 
     * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_container);
        initViews();
        initEvents();
        setSelected(0);


        CommonUtil.checkUpdate(this);
        // 应用宝省流量更新
        initYingYongBaoUpdate();


        initBaiduLocation();

        initShareParams();
    }

    private void initShareParams() {
        UMQQSsoHandler qqSsoHandler =
                new UMQQSsoHandler(MainActivity.this, Constants.APPID, Constants.QQAPPKEY);
        qqSsoHandler.addToSocialSDK();

        QZoneSsoHandler qZoneSsoHandler =
                new QZoneSsoHandler(MainActivity.this, Constants.APPID, Constants.QQAPPKEY);
        qZoneSsoHandler.addToSocialSDK();

        UMWXHandler wxHandler =
                new UMWXHandler(MainActivity.this, Constants.WEIXIN_APPID,
                        Constants.WEIXIN_APPSECRET);
        // 这里设置为false，授权页面可以再次出现。
        // 但是想要在授权页面实现用户切换确实不行的，需要去微信客户端才能实现用户切换
        // wxHandler.setRefreshTokenAvailable(false);
        wxHandler.addToSocialSDK();

        UMWXHandler wxCircleHandler =
                new UMWXHandler(MainActivity.this, Constants.WEIXIN_APPID,
                        Constants.WEIXIN_APPSECRET);
        wxCircleHandler.setToCircle(true);
        wxCircleHandler.addToSocialSDK();
    }


    /**
     * 应用程序开启时，开启百度定位
     */
    private void initBaiduLocation() {
        locationManager = BaiDuLocationManager.getInstance(MainActivity.this);
        locationManager.startLoacation(MainActivity.this, new IRequest<Location>() {
            @Override
            public void request(Location t) {
                // Toast.makeText(getBaseContext(), "定位成功" + t == null ? "1" : t.lat + "",
                // 0).show();
                if (t != null && t.lat != 0 && t.lon != 0) {
                    Constants.location_lat = t.lat;
                    Constants.location_lon = t.lon;
                    Constants.location_address = t.address;
                    Constants.location_city = t.city;
                    locationManager.stopLocation();
                }
            }
        });
    }

    private void initYingYongBaoUpdate() {
        // SelfUpdateHelper.initSelfUpdate(getApplicationContext(), 1234, "",
        // mITMSelfUpdateSDKListener);
    }

    public View getDrawerLayout() {
        return mDrawerLayout;
    }



    private void initViews() {
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        CommonParameter.sScreenWidth = metric.widthPixels;
        CommonParameter.sScreenHeight = metric.heightPixels;
        MoccaPreferences.sScreenWidth.put(metric.widthPixels);
        MoccaPreferences.sScreenHeight.put(metric.heightPixels);


        joinOutReciver = new JoinOutReciver();
        registerReceiver(joinOutReciver, new IntentFilter(Constants.JOIN_OUT_GROUP));

        loginSuccessReceiver = new LoginSuccessReceiver();
        registerReceiver(loginSuccessReceiver, new IntentFilter(
                Constants.ACTION_LOGIN_STATE_CHANGED));

        mDrawerLayout = (DrawerLayout) this.findViewById(R.id.drawer_layout);
        mDrawerLayout.setDrawerListener(taggle);

        // left_drawer = (InterceptListView) this.findViewById(R.id.left_drawer);
        // Drawable background = left_drawer.getBackground();
        // background.setAlpha(160);
        // drawerAdapter = new DrawerAdapter();
        // left_drawer.setAdapter(drawerAdapter);
        // getMineGroups();

        taggle =
                new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.icon, R.string.draw_open,
                        R.string.draw_close) {
                    @Override
                    public void onDrawerClosed(View drawerView) {
                        super.onDrawerClosed(drawerView);
                    }

                    @Override
                    public void onDrawerOpened(View drawerView) {
                        super.onDrawerOpened(drawerView);
                    }
                };

        vBottomTabs =
                new View[] {findViewById(R.id.bottom_tab_bar_home),
                        findViewById(R.id.bottom_tab_bar_group),
                        findViewById(R.id.bottom_tab_bar_shop),
                        findViewById(R.id.bottom_tab_bar_mine)};

        vNoticeMessageLabelIcon = findViewById(R.id.iv_push);

        mNoticeReceiver = new NoticeReceiver();
        registerReceiver(mNoticeReceiver, new IntentFilter(Constants.KEY_NOTICE_STATE_CHANGED));

    }

    private void initEvents() {
        findViewById(R.id.bottom_tab_bar_post).setOnClickListener(this);
        for (int i = 0; i < vBottomTabs.length; i++) {
            final int temp = i;
            vBottomTabs[i].setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    setSelected(temp);
                }
            });
        }
    }

    private void setSelected(int position) {
        if (mCurrentSelectedPosition == position) {
            return;
        }

        try {
            Fragment fragment = mFragmentMaps.get(position);
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            // hide the old Fragment
            if (mCurrentSelectedPosition != -1) {
                transaction.hide(mFragmentMaps.get(mCurrentSelectedPosition));
            }
            if (fragment == null) {
                fragment = (Fragment) mFragments[position].newInstance();
                Bundle bundle = new Bundle();
                if ("MainFragment_New".equals(fragment.getClass().getSimpleName())) {
                    mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                } else {
                    mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                }
                fragment.setArguments(bundle);
                mFragmentMaps.put(position, fragment);
                transaction.add(R.id.container, fragment).commit();
                // transaction.replace(R.id.container, fragment).commit();
            } else {
                if ("MainFragment_New".equals(fragment.getClass().getSimpleName())) {
                    mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                } else {
                    mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                }
                transaction.show(fragment);
                transaction.commit();
            }
            mCurrentSelectedPosition = position;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


        for (int i = 0; i < vBottomTabs.length; i++) {
            if (i == position) {
                vBottomTabs[i].setSelected(true);
            } else {
                vBottomTabs[i].setSelected(false);
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        // super.onSaveInstanceState(outState);
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.bottom_tab_bar_post:
                // showPostDialog();
                if (UserState.isLogged(MainActivity.this)) {
                    startActivity(new Intent(getBaseContext(), SelectPostModeActivity.class));
                    overridePendingTransition(R.anim.tran_in, R.anim.tran_out);
                    // overridePendingTransition(0, 0);
                }
                break;

            default:
                break;
        }
    }


    /**
     * 发帖 PopupWindow
     */
    // private void showPostDialog() {
    // final Dialog alertDialog = new Dialog(getApplicationContext(), R.style.custom_dlg_new);
    // LayoutInflater inflater =
    // (LayoutInflater) getApplicationContext().getSystemService(
    // Context.LAYOUT_INFLATER_SERVICE);
    // View viewLayout = inflater.inflate(R.layout.activity_select_post_mode, null);
    // final int[] ids = new int[] {R.id.tv_text, R.id.tv_camera, R.id.tv_photo};
    // final Map<Integer, View> mapViews = new HashMap<Integer, View>();
    // for (int i = 0; i < ids.length; i++) {
    // View view = viewLayout.findViewById(ids[i]);
    // mapViews.put(i, view);
    // }
    // final View cacel = viewLayout.findViewById(R.id.close);
    // final Handler mHandler = new Handler() {
    // @Override
    // public void handleMessage(Message msg) {
    // if (msg.what < 10) {
    // View view = mapViews.get(msg.what);
    // view.setVisibility(View.VISIBLE);
    // view.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),
    // R.anim.in_translate_top));
    // } else {
    // View view = mapViews.get(msg.what - 10);
    // view.setVisibility(View.INVISIBLE);
    // Animation outAnimation =
    // AnimationUtils.loadAnimation(getApplicationContext(),
    // R.anim.out_translate_top);
    // if (view.getId() == R.id.tv_text) {
    // outAnimation.setAnimationListener(new AnimationListener() {
    // @Override
    // public void onAnimationStart(Animation animation) {
    // cacel.setClickable(false);
    // }
    //
    // @Override
    // public void onAnimationRepeat(Animation animation) {}
    //
    // @Override
    // public void onAnimationEnd(Animation animation) {
    // alertDialog.dismiss();
    // }
    // });
    // }
    // view.startAnimation(outAnimation);
    // }
    // }
    // };
    // final OnClickListener cancelClickListener = new OnClickListener() {
    // @Override
    // public void onClick(View v) {
    // cacel.setVisibility(View.GONE);
    // mHandler.sendEmptyMessageDelayed(10, 50);
    // mHandler.sendEmptyMessageDelayed(11, 100);
    // mHandler.sendEmptyMessageDelayed(12, 80);
    // mHandler.sendEmptyMessageDelayed(13, 0);
    // mHandler.sendEmptyMessageDelayed(14, 30);
    // }
    // };
    // final OnClickListener onBtnClick = new View.OnClickListener() {
    // @Override
    // public void onClick(View v) {
    // switch (v.getId()) {
    // case R.id.tv_text:// 发送文字
    // Intent intent =
    // new Intent(getApplicationContext(), PostMessageActivity.class);
    // startActivity(intent);
    // alertDialog.dismiss();
    // break;
    // case R.id.tv_camera:
    // takePhoto();
    // break;
    // case R.id.tv_photo:
    // break;
    //
    // }
    // cancelClickListener.onClick(v);
    // }
    // };
    // cacel.setOnClickListener(cancelClickListener);
    // alertDialog.setContentView(viewLayout);
    // Window window = alertDialog.getWindow();
    // WindowManager.LayoutParams params = window.getAttributes();
    // params.gravity = Gravity.CENTER;
    // params.height = LayoutParams.MATCH_PARENT;
    // params.width = LayoutParams.MATCH_PARENT;
    // params.windowAnimations = R.style.custom_dlg_new;
    // alertDialog.getWindow().setAttributes(params);
    // alertDialog.setOnShowListener(new OnShowListener() {
    // @Override
    // public void onShow(DialogInterface dialog) {
    // if (magin == 0) {
    // int width = mapViews.get(0).getWidth();
    // magin = (widthPixels - width * 3) / 4;
    // }
    // mapViews.get(0).setOnClickListener(onBtnClick);
    // for (int i = 1; i < ids.length; i++) {
    // RelativeLayout.LayoutParams layoutParams =
    // (android.widget.RelativeLayout.LayoutParams) mapViews.get(i)
    // .getLayoutParams();
    // if (i == 3) {
    // layoutParams.topMargin = magin;
    // } else {
    // layoutParams.leftMargin = magin;
    // }
    // mapViews.get(i).setLayoutParams(layoutParams);
    // mapViews.get(i).setOnClickListener(onBtnClick);
    // }
    // mHandler.sendEmptyMessageDelayed(0, 50);
    // mHandler.sendEmptyMessageDelayed(1, 100);
    // mHandler.sendEmptyMessageDelayed(2, 80);
    // mHandler.sendEmptyMessageDelayed(3, 0);
    // mHandler.sendEmptyMessageDelayed(4, 30);
    // }
    // });
    // alertDialog.show();
    // }

    /**
     * 拍照
     */
    private void takePhoto() {
        mCameraFilePath =
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/happypet/pic"
                        + File.separator + System.currentTimeMillis() + ".jpg";
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
        startActivityForResult(intent, PUBLISHPOSTS.CAMERA);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mNoticeReceiver);
        unregisterReceiver(joinOutReciver);
        unregisterReceiver(loginSuccessReceiver);
        locationManager.stopLocation();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - mLastBackPressTime > SPACETIME) {
                mLastBackPressTime = System.currentTimeMillis();
                Toast.makeText(getBaseContext(), "再按一次退出", Toast.LENGTH_SHORT).show();
                return true;
            } else {
                finish();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    class NoticeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (NoticeLabel.sHasNewMessageNotice) {
                vNoticeMessageLabelIcon.setVisibility(View.VISIBLE);
            } else {
                vNoticeMessageLabelIcon.setVisibility(View.GONE);
            }
        }

    }


    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getPackageName());
        MobclickAgent.onPause(this);
        JPushInterface.onPause(getBaseContext());
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(getPackageName());
        MobclickAgent.onResume(this);
        JPushInterface.onResume(getBaseContext());

        if (MoccaPreferences.isGude.get()) {// 是否显示引导，默认第一次显示
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    MoccaPreferences.isGude.put(false);
                    CommonUtil.showHelpPopupWindow(MainActivity.this, R.layout.layout_helpguid,
                            R.drawable.home_help, findViewById(R.id.drawer_layout));
                }
            }, 200);
        }
    }


    protected String mResult = "0";
    private String mCameraFilePath;

    private class JoinOutReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {}
    }

    private class LoginSuccessReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {}
    }


    /**
     * 应用宝省流量更新
     */
    // private final ITMSelfUpdateSDKListener mITMSelfUpdateSDKListener =
    // new ITMSelfUpdateSDKListener() {
    // /**
    // * (只是checkupdate检查)增加接口给调用方 检查自更新 是否有更新包 ，如果有更新包，则返回新包大小、增量包大小
    // *
    // * @param updateInfo 这个参数，当继续往下走，下载 合成时，要传回来给接口downloadGenApk
    // */
    //
    // @Override
    // public void OnCheckNeedUpdateInfo(TMSelfUpdateSDKUpdateInfo arg0) {
    //
    // }
    //
    // /**
    // * (1) 省流量更新，跳应用宝进行自更新：<br />
    // * 当已经安装应用宝 或者 开始没安装下载后已安装应用宝onresume，通过opensdk跳应用宝详情页更新，下载调用方更新包的应用宝ipc来的进度回调。<br />
    // * <br />
    // * (2) 普通更新，使用更新sdk、下载sdk、open SDK实现第三方应用自更新:<br />
    // * sdk下载调用方新包或者patch包的进度回调(使用sdk自更新)
    // *
    // * @param url 当前任务的url
    // * @param receiveDataLen 已经接收的数据长度
    // * @param totalDataLen 全部需要接收的数据长度（如果无法获取目标文件的总长度，此参数返回 －1）
    // */
    //
    // @Override
    // public void OnDownloadAppProgressChanged(long arg0, long arg1) {
    //
    // }
    //
    // /**
    // * (1) 省流量更新，跳应用宝进行自更新：<br />
    // * 当已经安装应用宝 或者 开始没安装下载后已安装应用宝onresume，通过opensdk跳应用宝详情页更新，下载调用方更新包的应用宝ipc来的状态回调 。<br />
    // * <br />
    // * (2) 普通更新，使用更新sdk、下载sdk、open SDK实现第三方应用自更新:<br />
    // * 使用更新sdk、下载sdk、open SDK自更新时，TMSelfUpdateSDKTaskState的状态变化回调，目前只有自更新成功、失败、下载中 三个状态
    // * 。<br />
    // * <br />
    // *
    // * @param state 下载状态 TMAssistantDownloadSDKTaskState(省流量更新，跳应用宝进行自更新) 或
    // * TMSelfUpdateSDKTaskState(使用sdk自更新)
    // * @param errorCode TMAssistantDownloadSDKErrorCode(省流量更新，跳应用宝进行自更新) 或
    // * TMSelfUpdateSDKErrorCode(使用sdk自更新) 错误码
    // * @param errorMsg 错误信息
    // */
    //
    // @Override
    // public void OnDownloadAppStateChanged(int arg0, int arg1, String arg2) {
    //
    // }
    //
    // /**
    // * 省流量更新，跳应用宝进行自更新：当没有安装应用宝时，下载sdk下载应用宝包的进度回调(可选)
    // *
    // * @param url 当前任务的url
    // * @param receiveDataLen 已经接收的数据长度
    // * @param totalDataLen 全部需要接收的数据长度（如果无法获取目标文件的总长度，此参数返回 －1）
    // */
    // @Override
    // public void OnDownloadYYBProgressChanged(String url, long receiveDataLen,
    // long totalDataLen) {
    //
    // }
    //
    //
    // /**
    // * 省流量更新，跳应用宝进行自更新：当没有安装应用宝时，下载sdk下载应用宝包的状态回调 (可选)
    // *
    // * @param url 指定任务的url
    // * @param state 下载状态: 取自 TMAssistantDownloadSDKTaskState.DownloadSDKTaskState_*
    // * @param errorCode 错误码
    // * @param errorMsg 错误描述，有可能为null
    // */
    // @Override
    // public void OnDownloadYYBStateChanged(String url, int state, int errorCode,
    // String errorMsg) {}
    // };



}
